//登录
const jwt = require('jsonwebtoken')
const secretKey = 'GSX No1 ^_^'
let db = require("../db/index")
const login = (req, res) => {
    var sql = 'select * from login where name=? and password=?'
    db.query(sql, [req.body.name, req.body.password], (err, data) => {
        if (err) {
            return res.send({
                status: 400,
                message: "登录失败"
            })
        }
        if (data.length > 0) {
            req.session.user = req.body
            req.session.islogin = true
            const tokenStr = jwt.sign({
                username: req.session.user.name
            }, secretKey, { expiresIn: "600s" })
            res.send({
                status: 200,
                message: "登录成功",
                name: req.body.name,
                token: 'Bearer ' + tokenStr
            })
        } else {
            res.send({
                status: 202,
                message: '用户名或密码错误'
            })
        }
    })
}

const isLogin = (req, res) => {
    if (!req.session.islogin) {
        return res.send({
            status: 1,
            mag: 'fail'
        })
    }
    res.send({
        status: 0,
        msg: 'success'
    })
}
const zhuce = (req, res) => {
    var sql1 = "select * from login where name=?"
    var sql2 = 'INSERT INTO login(name,password) values (?,?)'
    console.log(req.body);
    db.query(sql1, [req.body.name], (err, data) => {
        if (err) {
            return res.send({
                status: 401,
                message: '操作失败'
            })
        }
        if (data.length > 0) {
            return res.send({
                status: 202,
                message: '用户名已存在'
            })
        } else {
            // return res.send({
            //   status: 200,
            //   message: '注册成功'
            // })
            db.query(sql2, [req.body.name, req.body.password], (err, data) => {
                if (err) {
                    return res.send({
                        status: 400,
                        message: '注册失败'
                    })
                } else {
                    return res.send({
                        status: 200,
                        message: '注册成功'
                    })
                }
            })
        }
    })
}
module.exports = {
    login, isLogin, zhuce
}